package crud.client.factory.form;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.validator.Validator;

import crud.client.data.Colonne;
import crud.client.data.DataView;
import crud.client.data.Donnee;
import crud.client.dialog.TableListGrid;
import crud.client.event.ColumnInitEvent;
import crud.client.factory.validator.field.ValidatorFactory;

public abstract class FormItemFactory implements Serializable, IsSerializable
{
	protected abstract FormItem newFormItem(Colonne colonne, DataView value);
	public abstract Serializable getData(Serializable key);
	public List<ValidatorFactory> validatorFactoryList = new ArrayList<ValidatorFactory>();

	public void setValueInRecord(final Record record, final TableListGrid tableListGrid, Donnee donnee)
	{
		// Sauvegarde du libelle de la donnée (pour affichage)
		if (donnee.getDataView().getLabel() != null)
		{
			record.setAttribute(donnee.getColonne().getCodeColonne(), donnee.getDataView().getLabel());
		} 	
	}

	/**
	 * Initialisation du composant<br><br>
	 * 
	 * <i>Une fois l'initialisation faite, le Handler doit impérativement lancer l'évènement</i>
	 * 
	 * @param colonne
	 * @param handlerManager
	 * @param columnInitEvent
	 */
	public void initialize(final Colonne colonne, final HandlerManager handlerManager, final ColumnInitEvent columnInitEvent)
	{
		handlerManager.fireEvent(columnInitEvent);
	}

	public String displayValue(String key)
	{
		return key;
	}

	public List<Validator> newValidatorList(Colonne colonne)
	{
		return new ArrayList<Validator>();
	}


	public FormItem newFormItem(Colonne colonne, Donnee donnee)
	{
		FormItem formItem;
		if (donnee != null)
		{
			formItem = newFormItem(colonne, donnee.getDataView());
		} else
		{
			formItem = newFormItem(colonne, (DataView) null);
		}

		formItem.setName(colonne.getCodeColonne());
		formItem.setTitle(colonne.getLibelle());
		formItem.setWrapTitle(false);
		formItem.setRequired(!colonne.isNullable());

		return formItem;
	}
	public List<ValidatorFactory> getValidatorFactoryList()
	{
		return validatorFactoryList;
	}
	public void addValidatorFactory(ValidatorFactory validatorFactory)
	{
		this.validatorFactoryList.add(validatorFactory);
	}
	
	public List<Validator> getValidatorListFromFactory(Colonne colonne)
	{
		List<Validator> validatorList = new ArrayList<Validator>();
		for (ValidatorFactory validatorFactory : validatorFactoryList)
		{
			validatorList.add(validatorFactory.newValidator(colonne));
		}
		
		return validatorList;
	}
}
